package edu.tjut.tjutcommunity.controller;


import edu.tjut.tjutcommunity.entity.*;
import edu.tjut.tjutcommunity.httpInterface.XXMHHttp;
import edu.tjut.tjutcommunity.service.PostService;
import edu.tjut.tjutcommunity.service.UserService;
import edu.tjut.tjutcommunity.utils.JWTUtils;
import edu.tjut.tjutcommunity.utils.UserUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

import static edu.tjut.tjutcommunity.utils.PairUtils.getPair;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yhh
 * @since 2022-04-14
 */
@RestController
@RequestMapping("/user")
public class UserController {

    final
    UserService userService;
    final
    PostService postService;

    public UserController(UserService userService, PostService postService) {
        this.userService = userService;
        this.postService = postService;
    }

    @PostMapping("/updateusername")
    public Message updateUsername(@RequestParam("name") String name) {
        String stuId = UserUtil.getCurStuId();
        if (userService.updateUsernameById(stuId, name)) {
            return Message.ok(getPair("msg", "更改成功"));
        }
        return Message.failed("更改失败");
    }

    @PostMapping("/checkUsername")
    public Message checkUsername(@RequestParam("name") String name) {
        if (userService.checkUsername(name)) {
            return Message.ok(new Pair<>("msg", "该名称可用"));
        }
        return Message.failed("该名称已存在");
    }

    @PostMapping("/mypost")
    public Message myPost(@RequestParam("pageNo") Integer pageNo, @RequestParam(value = "keyword", required = false) String keyword) {
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        PageResult<Post> posts = postService.getMyPost(user.getUid(), pageNo, keyword);
        if (posts.getResult().isEmpty()) {
            return Message.empty();
        }
        return Message.ok(posts);

    }

    @PostMapping("/checkUser")
    public Message checkUser(@RequestBody SchoolCookie cookie, HttpServletResponse rs) {
        //获取cookie，请求学校接口，获取个人信息，登入或注册。再返回UserInfo和token。
        User user = userService.checkCookieFromXXMH(cookie);
        if (user == null) return Message.failed("失败");
        rs.addHeader("token", JWTUtils.createToken(user.getStudentId()));

        return Message.ok(user);
    }
    @GetMapping("/getUserinfo")
    public Message getUserinfo() {
        String stuId = UserUtil.getCurStuId();
        User user = userService.getUserByStuId(stuId);
        return Message.ok(user);
    }



}

